require 'digest/sha2'

class User < ActiveRecord::Base
  attr_protected :hashed_password
  attr_accessor :password, :password_confirmation

  validates_presence_of :username, :message => "必须要提供登录用户名"
  
  validates_presence_of :password, :if => :password_required?, :message => "必须要设置登录密码"
  validates_presence_of :password_confirmation, :if => :password_required?, :message => "必须要提供确认密码"
  validates_confirmation_of :password, :if => :password_required?, :message => "密码输入不一致"
  validates_uniqueness_of :username, :case_sensitive => false, :message => "用户名已被注册"
  
  validates_length_of :username, :in => 4..20, :message => "用户名长度必须在4到20个字符之间"  
  validates_length_of :password, :in => 4..20, :if => :password_required?, :message => "密码长度必须在4到20个字符之间"
  
  HUMANIZED_ATTRIBUTES = {
    :username => "用户名称",
    :password => "用户密码",
    :password_confirmation => "确认密码"
  }

  def self.human_attribute_name(attr)
    HUMANIZED_ATTRIBUTES[attr.to_sym] || super
  end

  def password_required?
    self.hashed_password.blank? || !self.password.blank?
  end

  def self.encrypt(string)
    return Digest::SHA256.hexdigest(string)
  end

  def before_save
    self.hashed_password = User.encrypt(password) if !self.password.blank?
  end

  def self.authenticate(username, password)
    find(:first, :conditions =>
        ["username = ? and hashed_password = ?", username, User.encrypt(password)])
  end
  
end